package com.tron.game.jobs;


import com.alibaba.fastjson.JSONObject;
import com.tron.game.Lira;
import com.tron.game.LiraHelper;
import com.tron.game.configs.TronConfig;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.tron.trident.abi.FunctionEncoder;
import org.tron.trident.abi.FunctionReturnDecoder;
import org.tron.trident.abi.TypeReference;
import org.tron.trident.abi.datatypes.*;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.core.transaction.TransactionBuilder;
import org.tron.trident.proto.Chain;
import org.tron.trident.proto.Contract;
import org.tron.trident.proto.Response;
import org.tron.trident.utils.Numeric;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tuples.generated.Tuple14;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;

/**
 * 同步用户信息Job
 * @author pan_junbiao
 **/
@DisallowConcurrentExecution

public class CheckBscJob extends QuartzJobBean
{
    private static final Logger sysLog = LoggerFactory.getLogger(CheckBscJob.class);
    @Autowired
    TronConfig tronConfig;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext)
    {

        //获取当前时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //打印信息
        System.out.println("检查数据:当前时间：" + dateFormat.format(date));
        boolean check= false;
        try {
            check = CheckGame();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //System.out.println("检查结果：" +(check?"已到时需要开奖":"未到结束时间"));
        sysLog.error("检查结果：" +(check?"已到时需要开奖":"未到结束时间"));
        if(check)
        {
            String Transaction_Id= null;
            try {
                Transaction_Id = PrizeGame();
            } catch (Exception e) {
                e.printStackTrace();
            }
            sysLog.error("开奖：" + Transaction_Id);
        }else{
            try {
                long over_time = getCurrentRoundInfo();
                long now = getNow();
                long advance_seconds = 2 * 60 * 60;
                sysLog.error("本局结束时间:"+new Date(over_time*1000)+"\r\n"+"现在时间:"+new Date(now*1000));
                if (now + advance_seconds >= over_time) {
                    BuyToken();
                    sysLog.error("自动购买");
                }
            }catch (Exception ex)
            {

            }
        }

        System.out.println("----------------------------------------");
    }
    private  boolean CheckGame() throws Exception {
        Lira lira= LiraHelper.getInstance();
        Boolean askprice_result1= lira.checkGameAndPrize().send();
        return askprice_result1;

    }

    private String PrizeGame() throws Exception {
        Lira lira=LiraHelper.getInstance();

        TransactionReceipt askprice_result1= lira.PrizeGame().send();
        return  askprice_result1.getTransactionHash();
    }

    String BuyToken() throws Exception {
        Lira lira = LiraHelper.getInstance();

        if (lira == null) {

            return "fail";
        }
        BigInteger price= lira.askprice().send();

        TransactionReceipt transactionReceipt= lira.buy_token("0xEF000629F1C5A560A515b5c38cd0EF03f8a5d704",price).send();
        return transactionReceipt.getBlockHash();

    }


     long getCurrentRoundInfo() throws Exception {
         //Nile test net, using a node from Nile official website
         Lira lira = LiraHelper.getInstance();
         JSONObject object = new JSONObject();

//            1  uint256 game_id,
//            2  string memory name,
//            3    uint256 begin_time,
//            4    uint256 game_times,
//            5   uint256 last_buy_time,
//            6    uint256 over_time,
//            7    uint256 price,
//            8    uint256 price_upper_rate,
//            9    Entitys.GameStatus status,
//            10    uint256 prize_value,
//            11    uint256 bonus_value,
//            12    uint256 buy_count,
//            13   address last_buy_user_address,
//            14    uint256 next_change_rate_count
         Tuple14<BigInteger, String, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, String, BigInteger>
                 res = lira.getCurrentRoundInfo().send();


         BigInteger game_id = res.component1();
         String name = res.component2();
         BigInteger begin_time = res.component3();
         BigInteger game_times = res.component4();
         BigInteger last_buy_time = res.component5();
         BigInteger over_time = res.component6();
         BigInteger price = res.component7();
         BigInteger price_upper_rate = res.component8();
         BigInteger status = res.component9();
         BigInteger prize_value = res.component10();
         BigInteger bonus_value = res.component11();
         BigInteger buy_count = res.component12();
         String last_buy_user_address = res.component13();
         BigInteger next_change_rate_count = res.component14();


         //string
         object.put("game_id", game_id);
         object.put("name", name);
         object.put("begin_time", begin_time);
         object.put("begin_time_date", new Date(begin_time.longValue() * 1000));

         object.put("game_times", game_times);
         object.put("last_buy_time", last_buy_time);
         object.put("last_buy_time_date", new Date(last_buy_time.longValue() * 1000));

         object.put("over_time", over_time);
         object.put("over_time_date", new Date(over_time.longValue() * 1000));

         object.put("price", price.longValue() / Math.pow(10, 6));
         object.put("price_upper_rate", price_upper_rate.longValue() / Math.pow(10, 18));
         object.put("prize_value", prize_value.longValue() / Math.pow(10, 6));
         object.put("buy_count", buy_count);
         object.put("last_buy_user_address", last_buy_user_address);
         object.put("next_change_rate_count", next_change_rate_count);
         return over_time.longValue();
    }

    long getNow() throws Exception {
        Lira lira = LiraHelper.getInstance();

        if (lira == null) {

            return -1;
        }
        BigInteger result=lira.getNow().send();
        return  result.longValue();
    }
}
